package com.dqp.cslggroup.LostAndFound;

import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.DecelerateInterpolator;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;

import androidx.appcompat.widget.Toolbar;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.constraintlayout.widget.Group;

import com.dqp.cslggroup.R;
import com.dqp.cslggroup.UI.BaseActivity;
import com.dqp.cslggroup.Util.UiUtils;
import com.dqp.cslggroup.Web.web;
import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.util.Objects;

public class Lost_found extends BaseActivity {
    private String Lose_url = "http://www.cslggroup.top/lostproperty/lose.html";
    private String find_url = "http://www.cslggroup.top/lostproperty/find.html";
    private String main_url = "http://www.cslggroup.top/lostproperty/main.php";
    private WebView webView;
    private FloatingActionButton mAdd;
    private FloatingActionButton mLike;
    private FloatingActionButton mLose;
    private FloatingActionButton mFind;
    private Group likeGroup;
    private Group FindGroup;
    private Group LoseGroup;
    private AnimatorSet animatorSet;
    private int radius;
    private int width;
    private ProgressBar pb;
    private LinearLayout mErrorView;
    private boolean loadError = false;

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.lost_found);
        Toolbar toolbar = findViewById(R.id.include_toolbar);
        toolbar.setTitle("");
        setSupportActionBar(toolbar);
        Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
        init_web();
        setAccept();
        initWidget();
        initListener();
        re_button();
        webView.loadUrl(main_url);
    }

    @SuppressLint("SetJavaScriptEnabled")
    private void init_web() {
        mErrorView = findViewById(R.id.web_error);
        webView = findViewById(R.id.web_3);
        webView.clearCache(true);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.setWebViewClient(new WebViewClient() {
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }

            @SuppressLint("RestrictedApi")
            @Override
            public void onReceivedError(WebView view, int errorCode,
                                        String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
                view.setVisibility(View.GONE);
                mAdd.setVisibility(View.GONE);
                mErrorView.setVisibility(View.VISIBLE);
                loadError = true;
            }

            @SuppressLint("RestrictedApi")
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                if (!loadError) {
                    mErrorView.setVisibility(View.GONE);
                    webView.setVisibility(View.VISIBLE);
                    mAdd.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    public void re_button() {
        Button re = findViewById(R.id.re_web);
        re.setOnClickListener(view -> {
            mErrorView.setVisibility(View.GONE);
            loadError = false;
            webView.loadUrl(main_url);
        });
    }


    @Override
    protected void onResume() {
        super.onResume();
        mAdd.post(() -> width = mAdd.getMeasuredWidth()); // 动态获取FloatingActionButton的宽
        radius = UiUtils.dp2px(this, 80);   // 在xml文件里设置的半径
    }

    private void initWidget() {
        mAdd = findViewById(R.id.fab_add);
        mLike = findViewById(R.id.fab_like);
        mLose = findViewById(R.id.fab_top);
        mFind = findViewById(R.id.fab_write);
        likeGroup = findViewById(R.id.gp_like);
        FindGroup = findViewById(R.id.gp_write);
        LoseGroup = findViewById(R.id.gp_top);
        pb = findViewById(R.id.pb);
        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                // TODO 自动生成的方法存根
                if (newProgress == 100) {
                    pb.setVisibility(View.GONE);//加载完网页进度条消失
                } else {
                    pb.setVisibility(View.VISIBLE);//开始加载网页时显示进度条
                    pb.setProgress(newProgress);//设置进度值
                }

            }
        });
        mFind.setOnClickListener(view -> {
            Intent intent = new Intent(Lost_found.this, web.class);
            intent.putExtra("url", Lose_url);
            startActivity(intent);


        });
        mLose.setOnClickListener(view -> {
            Intent intent = new Intent(Lost_found.this, web.class);
            intent.putExtra("url", find_url);
            startActivity(intent);
        });
        mLike.setOnClickListener(view -> {
            Intent intent = new Intent(Lost_found.this, chat.class);
            startActivity(intent);
        });

        // 将三个弹出的FloatingActionButton隐藏
        setViewVisible(false);
    }

    private void setViewVisible(boolean isShow) {
        likeGroup.setVisibility(isShow ? View.VISIBLE : View.GONE);
        FindGroup.setVisibility(isShow ? View.VISIBLE : View.GONE);
        LoseGroup.setVisibility(isShow ? View.VISIBLE : View.GONE);
    }

    private void initListener() {
        mAdd.setOnClickListener(v -> {
            // 播放动画的时候不可以点击
            if (animatorSet != null && animatorSet.isRunning())
                return;
            // 判断播放显示还是隐藏动画
            if (likeGroup.getVisibility() != View.VISIBLE) {
                animatorSet = new AnimatorSet();
                ValueAnimator likeAnimator = getValueAnimator(mLike, false, likeGroup, 0);
                ValueAnimator writeAnimator = getValueAnimator(mFind, false, FindGroup, 45);
                ValueAnimator topAnimator = getValueAnimator(mLose, false, LoseGroup, 90);
                animatorSet.playSequentially(likeAnimator, writeAnimator, topAnimator);
                animatorSet.start();
            } else {
                animatorSet = new AnimatorSet();
                ValueAnimator likeAnimator = getValueAnimator(mLike, true, likeGroup, 0);
                ValueAnimator writeAnimator = getValueAnimator(mFind, true, FindGroup, 45);
                ValueAnimator topAnimator = getValueAnimator(mLose, true, LoseGroup, 90);
                animatorSet.playSequentially(topAnimator, writeAnimator, likeAnimator);
                animatorSet.start();
            }

        });
    }

    /**
     * 获取ValueAnimator
     *
     * @param button  FloatingActionButton
     * @param reverse 开始还是隐藏
     * @param group   Group
     * @param angle   angle 转动的角度
     * @return ValueAnimator
     */
    private ValueAnimator getValueAnimator(final FloatingActionButton button,
                                           final boolean reverse, final Group group, final int angle) {
        ValueAnimator animator;
        if (reverse)
            animator = ValueAnimator.ofFloat(1, 0);
        else
            animator = ValueAnimator.ofFloat(0, 1);
        animator.addUpdateListener(animation -> {
            float v = (float) animation.getAnimatedValue();
            ConstraintLayout.LayoutParams params
                    = (ConstraintLayout.LayoutParams) button.getLayoutParams();
            params.circleRadius = (int) (radius * v);
            params.width = (int) (width * v);
            params.height = (int) (width * v);
            button.setLayoutParams(params);
        });
        animator.addListener(new SimpleAnimation() {
            @Override
            public void onAnimationStart(Animator animation) {
                group.setVisibility(View.VISIBLE);
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                if (group == likeGroup && reverse) {
                    setViewVisible(false);
                }
            }
        });
        animator.setDuration(300);
        animator.setInterpolator(new DecelerateInterpolator());
        return animator;
    }

    abstract class SimpleAnimation implements Animator.AnimatorListener {
        @Override
        public void onAnimationStart(Animator animation) {
        }

        @Override
        public void onAnimationEnd(Animator animation) {
        }

        @Override
        public void onAnimationCancel(Animator animation) {
        }

        @Override
        public void onAnimationRepeat(Animator animation) {
        }
    }

    public void setAccept() {
        SharedPreferences sp = getSharedPreferences("luru_accept", MODE_PRIVATE);
        boolean accept = sp.getBoolean("luru_accept", true);
        if (accept) {
            tip();
        }
    }

    public void tip() {
        final com.dqp.cslggroup.UI.AlertDialog alertDialog = new com.dqp.cslggroup.UI.AlertDialog(Lost_found.this);
        alertDialog.builder();
        alertDialog.setGone()
                .setTitle("联系方式录入")
                .setMsg(this.getResources().getString(R.string.xytext))
                .setNegativeButton("前往录入", R.color.colorAccent, v -> {
                    Intent intent = new Intent(Lost_found.this, entry.class);
                    startActivity(intent);
                })
                .setPositiveButton("拒绝录入", R.color.colorAccent, v -> finish()).show();
    }


    @Override
    public void onBackPressed() {
        if (webView.canGoBack()) {
            if (webView.getUrl().equals(main_url)) {
                super.onBackPressed();
            } else {
                webView.goBack();
            }
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

}
